﻿using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Threading.BackgroundWorkers;

using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.Exporting;
using L._52ABP.Application.Dtos;

 
using JYJ.AiYard.Configuration;
using JYJ.AiYard.Debugging; 
using JYJ.AiYard.MultiTenancy;
using JYJ.AiYard.StationManagement.YardReport.Authorization;
using JYJ.AiYard.StationManagement.YardReport.Dtos;
using JYJ.AiYard.StationManagement.TbStations.Dtos;
using JYJ.AiYard.StationManagement.TbSales.Dtos;
using JYJ.AiYard.UserManagement.Users;
using JYJ.AiYard.StationManagement.TbStations;
using JYJ.AiYard.Organizations.Dtos;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using Aliyun.SDK.CCP.CCPClient;
using AlibabaCloud.TeaUtil.Models;
using Aliyun.SDK.CCP.CCPClient.Models;
using System.Net;
using System.IO;
using Microsoft.AspNetCore.Http;
using JYJ.AiYard.StationManagement.TbClientRegisters.Dtos;
using JYJ.AiYard.StationManagement.TbClientRegisters;
using JYJ.AiYard.EntityFrameworkCore;
using JYJ.AiYard.UserManagement.Users.Dtos;
using JYJ.AiYard.StationManagement.YardCommonHald;
using JYJ.AiYard.Authorization.Roles;
using System.Text;
using L._52ABP.Common.Net.MimeTypes;
using JYJ.AiYard.DataFileObjects.DataTempCache;


namespace JYJ.AiYard.StationManagement.YardReport
{
    [AbpAuthorize]
    public class TbrInYardApplicationService : AiYardAppServiceBase, ITbrInYardApplicationService
    {
        #region 构造函数    

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;

        private readonly IListExcelExporter _listExcelExporter;

        private readonly UserAppService _userApp;

        private readonly IConfigurationRoot _appConfiguration;

        private readonly IHostingEnvironment _env;

        protected IHttpContextAccessor _httpContext;

        private readonly IHttpService _httpService;

        private readonly RoleManager _roleManager;

        private readonly IDataTempFileCacheManager _dataTempFileCacheManager;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbrInYardApplicationService(
        IAiYardDbTableIssuedCard aiYardDbTableIssuedCard,
        IListExcelExporter listExcelExporter,
        UserAppService userApp,
        IHostingEnvironment env,
        IHttpService httpService,
        IHttpContextAccessor httpContextAccessor,
        RoleManager roleManager,
        IDataTempFileCacheManager dataTempFileCacheManager
        )
        {
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
            _listExcelExporter = listExcelExporter;
            _userApp = userApp;
            _env = env;
            _httpService = httpService;
            _appConfiguration = env.GetAppConfiguration();
            _httpContext = httpContextAccessor;
            _roleManager = roleManager;
            _dataTempFileCacheManager = dataTempFileCacheManager;
        }
        #endregion

        #region 查询进出场图片
        public async Task<Dictionary<string, string>> downloadImages2(int IN_OUT, int Id, long StationId)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            try
            {
                string StationNo = "";
                string inimage = "";
                string outimage = "";
                if (!_aiYardDbTableIssuedCard.GetImagesFileId2(IN_OUT, Id, StationId,ref StationNo,ref inimage,ref outimage))
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "未获取到进出场抓拍图片");
                    return result;
                }
                string host = "http://" + _httpContext.HttpContext.Request.Host.Host + ":6299";
                string webRootPath = _appConfiguration["ImageService"];
               
                string infileName = inimage != "" ? (inimage.Split('\\')[inimage.Split('\\').Length - 1].ToString()) : "";
                string outfileName = outimage != "" ? (outimage.Split('\\')[outimage.Split('\\').Length - 1].ToString()) : "";

                string infloderNo = inimage != "" ? (inimage.Split('\\')[inimage.Split('\\').Length - 2].ToString()) : "";
                string outfloderNo = outimage != "" ? (outimage.Split('\\')[outimage.Split('\\').Length - 2].ToString()) : "";
                if (File.Exists(webRootPath + "\\" + StationNo + "\\" + infloderNo + "\\" + infileName))
                {
                    inimage = host + "/" + StationNo + "/" + infloderNo + "/" + infileName;
                }
                if (File.Exists(webRootPath + "\\" + StationNo + "\\" + outfloderNo + "\\" + outfileName))
                {
                    outimage = host + "/" + StationNo + "/" + outfloderNo + "/" + outfileName;
                }
                //result.Add("inImage", inimage);
                //result.Add("outimage", outimage);
                result.Add("retype", "1");
                result.Add("stationNo", StationNo);
                result.Add("inImage", inimage);
                result.Add("outImage", outimage);
                result.Add("infloderNo", infloderNo);
                result.Add("outfloderNo", outfloderNo);
                return result;
            }
            catch (Exception ex) 
            {
                result.Add("retype", "2");
                result.Add("revalue", "加载图片错误，请重新尝试");
                Logger.Error(ex.Message);
                return result;
            }
        }
        public async Task<Dictionary<string, string>> downloadImages(int IN_OUT, int Id, long StationId)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            try
            {
                List<string> imgs = _aiYardDbTableIssuedCard.GetImagesFileId(IN_OUT, Id, StationId);
                if (imgs == null)
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "未获取到进出场抓拍图片");
                    return result;
                }
                string host = "http://" + _httpContext.HttpContext.Request.Host.Host + ":6298";
                string Aliyun_CCP_DomainId = _appConfiguration["AliyunCCP:Aliyun_CCP_DomainId"];
                string Aliyun_CCP_Appid = _appConfiguration["AliyunCCP:Aliyun_CCP_Appid"];
                string Aliyun_CCP_AppSecret = _appConfiguration["AliyunCCP:Aliyun_CCP_AppSecret"];
                string StationNo = imgs[0].Split('$')[0];
                string floderNo = imgs[0].Split('$')[1];
                string fileid = imgs[0].Split('$')[2];
                string filename = imgs[0].Split('$')[3];
                string webRootPath = _env.WebRootPath;
                if (!Directory.Exists(webRootPath + "/Temp/"))
                {
                    Directory.CreateDirectory(webRootPath + "/Temp/");
                }
                if (!Directory.Exists(webRootPath + "/Temp/Downloads/"))
                {
                    Directory.CreateDirectory(webRootPath + "/Temp/Downloads/");
                }
                if (!Directory.Exists(webRootPath + "/Temp/Downloads/" + StationNo + "/"))
                {
                    Directory.CreateDirectory(webRootPath + "/Temp/Downloads/" + StationNo + "/");
                }
                if (!Directory.Exists(webRootPath + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/"))
                {
                    Directory.CreateDirectory(webRootPath + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/");
                }
                result.Add("retype", "1");
                bool downin = true;
                bool downout = true;
                bool downopen = true;
                if (File.Exists(webRootPath + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/" + filename))
                {
                    downin = false;
                    result.Add("img_IN", host + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/" + filename);
                }
                if (IN_OUT == 2)
                {
                    string outfloderNo = imgs[1].Split('$')[1];
                    string outfileid = imgs[1].Split('$')[2];
                    string outfilename = imgs[1].Split('$')[3];
                    if (File.Exists(webRootPath + "/Temp/Downloads/" + StationNo + "/" + outfloderNo + "/" + outfilename))
                    {
                        downout = false;
                        result.Add("img_OUT", host + "/Temp/Downloads/" + StationNo + "/" + outfloderNo + "/" + outfilename);
                    }
                }
                if (IN_OUT == 3)
                {
                    if (File.Exists(webRootPath + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/" + filename))
                    {
                        downin = false;
                        result.Add("img_Open", host + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/" + filename);
                    }
                    
                }


                Config config = new Config();
                config.DomainId = Aliyun_CCP_DomainId;
                config.Protocol = "https";
                config.AccessKeyId = Aliyun_CCP_Appid;
                config.AccessKeySecret = Aliyun_CCP_AppSecret;
                Client client = new Client(config);
                Aliyun.SDK.CCP.CCPClient.Models.RuntimeOptions runtime = new Aliyun.SDK.CCP.CCPClient.Models.RuntimeOptions();
                 
                if (downin || (downopen && IN_OUT == 3))
                {
                    CCPGetDownloadUrlRequestModel cCPGet = new CCPGetDownloadUrlRequestModel();
                    cCPGet.Body = new CCPGetDownloadUrlRequest();
                    cCPGet.Body.DriveId = "1";
                    cCPGet.Body.FileId = fileid;
                    cCPGet.Body.FileName = filename;
                    cCPGet.Body.ExpireSec = 120;
                    GetDownloadUrlModel downloads = client.GetDownloadUrl(cCPGet, runtime);
                    if (downloads.Body.Url != "")
                    {
                        WebClient mywebClient = new WebClient();
                        //mywebClient.Headers.Add("Content-Type", "");
                        try
                        {
                            mywebClient.DownloadFile(downloads.Body.Url, webRootPath + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/" + filename);
                        }
                        catch (WebException ex)
                        {
                            if (ex.Response != null)
                            {
                                var response = ex.Response;
                                var dataStream = response.GetResponseStream();
                                var reader = new StreamReader(dataStream);
                                var details = reader.ReadToEnd();
                                Logger.Error(details);
                            }
                            Logger.Error(ex.Message);
                        }
                        if (File.Exists(webRootPath + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/" + filename))
                        {
                            try
                            {
                                FileStream file = File.Open(webRootPath + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/" + filename, FileMode.Open);
                                if (file.Length <= 0)
                                {
                                    file.Close();
                                    //再下载一次
                                    mywebClient.DownloadFile(downloads.Body.Url, webRootPath + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/" + filename);
                                }
                                else
                                {
                                    file.Close();
                                }
                            }
                            catch
                            {

                            }
                            if (IN_OUT == 3)
                            {
                                result.Add("img_Open", host + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/" + filename);
                            }
                            else
                            {
                                result.Add("img_IN", host + "/Temp/Downloads/" + StationNo + "/" + floderNo + "/" + filename);
                            }
                        }
                        else
                        {
                            if (IN_OUT == 3)
                            {
                                result.Add("img_Open", "无图片");
                            }
                            else
                            {
                                result.Add("img_IN", "无图片");
                            }
                        }
                    }
                    else
                    {
                        if (IN_OUT == 3)
                        {
                            result.Add("img_Open", "无图片");
                        }
                        else
                        {
                            result.Add("img_IN", "无图片");
                        }
                    }
                }
                if (downout && IN_OUT == 2)
                {
                    string outfloderNo = imgs[1].Split('$')[1];
                    string outfileid = imgs[1].Split('$')[2];
                    string outfilename = imgs[1].Split('$')[3];
                    if (!Directory.Exists(webRootPath + "/Temp/Downloads/" + StationNo + "/" + outfloderNo + "/"))
                    {
                        Directory.CreateDirectory(webRootPath + "/Temp/Downloads/" + StationNo + "/" + outfloderNo + "/");
                    }
                    CCPGetDownloadUrlRequestModel outcCPGet = new CCPGetDownloadUrlRequestModel();
                    outcCPGet.Body = new CCPGetDownloadUrlRequest();
                    outcCPGet.Body.DriveId = "1";
                    outcCPGet.Body.FileId = outfileid;
                    outcCPGet.Body.FileName = outfilename;
                    outcCPGet.Body.ExpireSec = 120;

                    GetDownloadUrlModel outdownloads = client.GetDownloadUrl(outcCPGet, runtime);
                    if (outdownloads.Body.Url != "")
                    {
                        WebClient mywebClient = new WebClient();
                        //mywebClient.Headers.Add("Content-Type", "");
                        try
                        {
                            mywebClient.DownloadFile(outdownloads.Body.Url, webRootPath + "/Temp/Downloads/" + StationNo + "/" + outfloderNo + "/" + outfilename);
                        }
                        catch (WebException ex)
                        {
                            if (ex.Response != null)
                            {
                                var response = ex.Response;
                                var dataStream = response.GetResponseStream();
                                var reader = new StreamReader(dataStream);
                                var details = reader.ReadToEnd();
                                Logger.Error(details);
                            }
                            Logger.Error(ex.Message);
                        }
                        if (File.Exists(webRootPath + "/Temp/Downloads/" + StationNo + "/" + outfloderNo + "/" + outfilename))
                        {
                            result.Add("img_OUT", host + "/Temp/Downloads/" + StationNo + "/" + outfloderNo + "/" + outfilename);
                        }
                        else
                        {
                            result.Add("img_OUT", "无图片");
                        }
                    }
                    else
                    {
                        result.Add("img_OUT", "无图片");
                    }
                }
                return result;
            }
            catch (Exception ex)
            {

                result.Add("revalue", "加载图片错误，请重新尝试");
                Logger.Error(ex.Message);
                return result;
            }
        }
        #endregion

        #region TbrInYard进场数据查询
        #region 分页查询
        /// <summary>
        /// TbrInYard进出数据查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrInYardQuery)]
        public YardPagedResult<TbrInYard> GetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrInYardInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrInYardInput>(json);
                YardPagedResult<TbrInYard> pr = _aiYardDbTableIssuedCard.GetTbrInYard(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<TbrInYard>();
            }

        }
        #endregion
        #region 进场导出数据
        /// <summary>
        /// 进场导出数据
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrInYardExportExcel)]
        public async Task<FileDto> GetToExcel(string json)
        {
            //try
            //{
            json = json.Replace("undefined", "");
            TbrInYardInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrInYardInput>(json);
            List<TbrInYard> pr = _aiYardDbTableIssuedCard.ExportTbrInYard(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByTbrInYard(pr);
            //}
            //catch (Exception e)
            //{
            //    return new FileDto();
            //}
        }
        #endregion
        #region 导出场内记录
        [AbpAuthorize(TbrInYardPermissions.TbrInYardExportInYard)]
        public async Task<FileDto> GetToSql(string json)
        {
            json = json.Replace("undefined", "");
            TbrInYardInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrInYardInput>(json);
            List<TbrInYardSql> pr = _aiYardDbTableIssuedCard.ExportInYardSql(tc, getBAccountQuery());
            StringBuilder builder = new StringBuilder();
            if (pr != null && pr.Count > 0)
            {
                
        
                foreach (var pp in pr)
                {
                    string strSql = $@" INSERT [dbo].[tY_InYard] ([tIN_ID], [tIN_CardType_ID], [tIN_CardType_Name], [tIN_CardNO], [tIN_Plate_Color], 
                                        [tIN_Time], [tIN_Mach_ID], [tIN_Mach_Name], [tIN_CPlate], [tIN_SPlate], [tIN_UserId], [tIN_UserNO], [tIN_UserName], 
                                        [tIN_Image1], [tIN_Image2], [tIN_Image3], [tIN_Image4], [tIN_Image5], [tIN_Op_Id], [tIN_Op_NO], [tIN_Op_Name], 
                                        [tIN_OP_Time], [tIN_Small], [tIN_Client_ID], [tIN_Yard_ID], [tIN_Class_ID], [tCard_Tag], [tCar_Color], [tPlate_Color], 
                                        [tCar_Type], [tPlate_Type], [tisPrivilege], [tnConfidence]) VALUES (
                                        {pp.tIN_ID}, 
                                        {pp.tIN_CardType_ID}, 
                                        N'{pp.tIN_CardType_Name}', 
                                        N'{pp.tIN_CardNO}', 
                                        {pp.tIN_Plate_Color}, 
                                        CAST(N'{pp.tIN_Time.ToString("yyyy-MM-dd HH:mm:ss")}' AS DateTime), 
                                        {pp.tIN_Mach_ID}, 
                                        N'{pp.tIN_Mach_Name}', 
                                        N'{pp.tIN_CPlate}', 
                                        N'{pp.tIN_SPlate}', 
                                        N'{pp.tIN_UserId}', 
                                        N'{pp.tIN_UserNO}', 
                                        N'{pp.tIN_UserName}', 
                                        N'{pp.tIN_Image1}', 
                                        N'{pp.tIN_Image2}', 
                                        N'{pp.tIN_Image3}', 
                                        N'{pp.tIN_Image4}', 
                                        N'{pp.tIN_Image5}', 
                                        N'{pp.tIN_Op_Id}', 
                                        N'{pp.tIN_Op_NO}', 
                                        N'{pp.tIN_Op_Name}', 
                                        CAST(N'{pp.tIN_OP_Time.ToString("yyyy-MM-dd HH:mm:ss")}' AS DateTime), 
                                        {(pp.tIN_Small?1:0)}, 
                                        N'{pp.tIN_Client_ID}', 
                                        {pp.tIN_Yard_ID}, 
                                        {pp.tIN_Class_ID}, 
                                        N'{pp.tCard_Tag}', 
                                        N'{pp.tCar_Color}', 
                                        N'{pp.tPlate_Color}', 
                                        N'{pp.tCar_Type}', 
                                        N'{pp.tPlate_Type}', 
                                        N'{pp.tisPrivilege}', 
                                        {pp.tnConfidence})" + "\n\t";
                    strSql = strSql + " GO \n\t";
                    builder.Append(strSql);
                }
            }
            var file = new FileDto(tc.Station_No+".sql", MimeTypeNames.ApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet);


            _dataTempFileCacheManager.SetFile(file.FileToken, System.Text.Encoding.UTF8.GetBytes(builder.ToString()));

            return file;
            //json = json.Replace("undefined", "");
            //TbrInYardInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrInYardInput>(json);
            //List<TbrInYard> pr = _aiYardDbTableIssuedCard.ExportTbrInYard(tc, getBAccountQuery());
            //if (pr == null || pr.Count <= 0)
            //{
            //    throw new Exception("无数据，请先查询再导入");
            //}
            //return _listExcelExporter.ExportToExcelByTbrInYard(pr);

        }
        #endregion
        #endregion

        #region TbrOutYard出场数据查询
        #region 分页查询
        /// <summary>
        /// TbrOutYard出场数据查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrOutYardQuery)]
        public YardPagedResult<TbrOutYard> TbrOutYardGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrOutYardInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrOutYardInput>(json);
                YardPagedResult<TbrOutYard> pr = _aiYardDbTableIssuedCard.GetTbrOutYard(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<TbrOutYard>();
            }

        }
        #endregion
        #region 出场导出数据
        /// <summary>
        /// 出场导出数据
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrOutYardExportExcel)]
        public async Task<FileDto> TbrOutYardGetToExcel(string json)
        {

            json = json.Replace("undefined", "");
            TbrOutYardInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrOutYardInput>(json);
            List<TbrOutYard> pr = _aiYardDbTableIssuedCard.ExportTbrOutYard(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByTbrOutYard(pr);

        }
        #endregion
        #endregion

        #region TbrOutYard出场数据查询版本2
        #region 分页查询
        /// <summary>
        /// TbrOutYard出场数据查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrOutYardQuery2)]
        public YardPagedResult2<DataTable> TbrOutYardGetPaged2(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrOutYardInput2 tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrOutYardInput2>(json);
                YardPagedResult2<DataTable> pr = _aiYardDbTableIssuedCard.GetTbrOutYard2(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult2<DataTable>();
            }

        }
        #endregion
        #region 出场导出数据
        /// <summary>
        /// 出场导出数据
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrOutYardExportExcel2)]
        public async Task<FileDto> TbrOutYardGetToExcel2(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrOutYardInput2 tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrOutYardInput2>(json);
                DataTable pr = _aiYardDbTableIssuedCard.ExportTbrOutYard2(tc, getBAccountQuery());
                if (pr == null || pr.Rows.Count <= 0)
                {
                    throw new Exception("无数据，请先查询再导入");
                }
                string fileName = Guid.NewGuid().ToString("D");
                string webRootPath = _env.WebRootPath;
                var fileDire = webRootPath + string.Format("/Temp/Downloads/", "");
                if (!Directory.Exists(fileDire))
                {
                    Directory.CreateDirectory(fileDire);
                }

                var filePath = fileDire + fileName + ".xls";

                AiYardDbNPOIExcel excel = new AiYardDbNPOIExcel();

                excel.ToExcel(pr, "车辆出场数据查询", "车辆出场数据查询", filePath);

                FileDto file = new FileDto("车辆出场数据查询.xls", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                file.FileToken = fileName + ".xls";
                return file;

            }
            catch (Exception ex)
            {
                throw new Exception("导出文件失败");
            }
        }
        #endregion
        #endregion

        #region TbrOpenGate车辆开闸数据查询
        #region 分页查询
        /// <summary>
        /// TbrOpenGate车辆开闸数据查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrOpenGateQuery)]
        public YardPagedResult<TbrOpenGate> TbrOpenGateGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrOpenGateInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrOpenGateInput>(json);
                YardPagedResult<TbrOpenGate> pr = _aiYardDbTableIssuedCard.GetTbrOpenGate(tc);

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<TbrOpenGate>();
            }

        }
        #endregion
        #region 车辆开闸导出数据
        /// <summary>
        /// 车辆开闸导出数据
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrOpenGateExportExcel)]
        public async Task<FileDto> TbrOpenGateGetToExcel(string json)
        {
            //try
            //{
            json = json.Replace("undefined", "");
            TbrOpenGateInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrOpenGateInput>(json);
            List<TbrOpenGate> pr = _aiYardDbTableIssuedCard.ExportTbrOpenGate(tc);
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByTbrOpenGate(pr);
            //}
            //catch (Exception e)
            //{
            //    return new FileDto();
            //}
        }
        #endregion
        #endregion

        #region TbrIssued车辆发行数据查询
        #region 分页查询
        /// <summary>
        /// TbrIssued发行车牌数据查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrIssuedQuery)]
        public YardPagedResult<TbrIssued> TbrIssuedGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrIssuedInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrIssuedInput>(json);
                YardPagedResult<TbrIssued> pr = _aiYardDbTableIssuedCard.GetTbrIssued(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<TbrIssued>();
            }

        }
        #endregion
        #region 发行车牌导出数据
        /// <summary>
        /// 发行车牌导出数据
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrIssuedExportExcel)]
        public async Task<FileDto> TbrIssuedGetToExcel(string json)
        {
            //try
            //{
            json = json.Replace("undefined", "");
            TbrIssuedInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrIssuedInput>(json);
            List<TbrIssued> pr = _aiYardDbTableIssuedCard.ExportTbrIssued(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByTbrIssued(pr);
            //}
            //catch (Exception e)
            //{
            //    return new FileDto();
            //}
        }
        #endregion
        #endregion

        #region TbrIssuedOpCard车辆操作报表
        #region 分页查询
        /// <summary>
        /// TbrIssuedOpCard车辆操作报表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrIssuedOpCardQuery)]
        public YardPagedResult<TbrIssuedOpCard> TbrIssuedOpCardGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrIssuedOpCardInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrIssuedOpCardInput>(json);
                YardPagedResult<TbrIssuedOpCard> pr = _aiYardDbTableIssuedCard.GetTbrIssuedOpCard(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<TbrIssuedOpCard>();
            }

        }
        #endregion
        #region 车辆操作导出数据
        /// <summary>
        /// 发卡导出数据
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrIssuedOpCardExportExcel)]
        public async Task<FileDto> TbrIssuedOpCardGetToExcel(string json)
        {
            //try
            //{
            json = json.Replace("undefined", "");
            TbrIssuedOpCardInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrIssuedOpCardInput>(json);
            List<TbrIssuedOpCard> pr = _aiYardDbTableIssuedCard.ExportTbrIssuedOpCard(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByTbrIssuedOpCard(pr);
            //}
            //catch (Exception e)
            //{
            //    return new FileDto();
            //}
        }
        #endregion
        #endregion

        #region TbrDiscount停车券明细表
        #region 分页查询
        /// <summary>
        /// TbrDiscount停车券明细表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrDiscountQuery)]
        public YardPagedResult2<DataTable> TbrDiscountGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrDiscountInput tc = YardCommonHald.Json.ToObject<TbrDiscountInput>(json);
                YardPagedResult2<DataTable> pr = _aiYardDbTableIssuedCard.GetTbrDiscount(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult2<DataTable>();
            }

        }
        #endregion
        #region 停车券明细表
        /// <summary>
        /// 发卡导出数据
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrDiscountExportExcel)]
        public async Task<FileDto> TbrDiscountGetToExcel(string json)
        {
            //try
            //{
            json = json.Replace("undefined", "");
            TbrDiscountInput tc = YardCommonHald.Json.ToObject<TbrDiscountInput>(json);
            List<TbrDiscount> pr = _aiYardDbTableIssuedCard.ExportTbrDiscount(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByTbrDiscount(pr);
            //}
            //catch (Exception e)
            //{
            //    return new FileDto();
            //}
        }
        #endregion
        #endregion

        #region TbrChangeClass交班统计报表
        #region 分页查询
        /// <summary>
        /// TbrChangeClass交班统计报表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrChangeClassQuery)]
        public YardPagedResult<TbrChangeClass> TbrChangeClassGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrChangeClassInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrChangeClassInput>(json);
                YardPagedResult<TbrChangeClass> pr = _aiYardDbTableIssuedCard.GetTbrChangeClass(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<TbrChangeClass>();
            }

        }
        #endregion
        #region 交班统计报表
        /// <summary>
        /// 发卡导出数据
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrChangeClassExportExcel)]
        public async Task<FileDto> TbrChangeClassGetToExcel(string json)
        {
            //try
            //{
            json = json.Replace("undefined", "");
            TbrChangeClassInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrChangeClassInput>(json);
            List<TbrChangeClass> pr = _aiYardDbTableIssuedCard.ExportTbrChangeClass(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByTbrChangeClass(pr);
            //}
            //catch (Exception e)
            //{
            //    return new FileDto();
            //}
        }
        #endregion
        #endregion

        #region TbrChangeClass交班统计报表版本2
        #region 分页查询
        /// <summary>
        /// TbrChangeClass交班统计报表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrChangeClassQuery2)]
        public YardPagedResult2<DataTable> TbrChangeClassGetPaged2(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrChangeClassInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrChangeClassInput>(json);
                YardPagedResult2<DataTable> pr = _aiYardDbTableIssuedCard.GetTbrChangeClass2(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult2<DataTable>();
            }

        }
        #endregion
        #region 交班统计报表
        /// <summary>
        /// 发卡导出数据
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrChangeClassExportExcel2)]
        public async Task<FileDto> TbrChangeClassGetToExcel2(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrChangeClassInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrChangeClassInput>(json);
                DataTable pr = _aiYardDbTableIssuedCard.ExportTbrChangeClass2(tc, getBAccountQuery());
                if (pr == null || pr.Rows.Count <= 0)
                {
                    throw new Exception("无数据，请先查询再导入");
                }
                string fileName = Guid.NewGuid().ToString("D");
                string webRootPath = _env.WebRootPath;
                var fileDire = webRootPath + string.Format("/Temp/Downloads/", "");
                if (!Directory.Exists(fileDire))
                {
                    Directory.CreateDirectory(fileDire);
                }

                var filePath = fileDire + fileName + ".xls";

                AiYardDbNPOIExcel excel = new AiYardDbNPOIExcel();

                excel.ToExcel(pr, "交班统计报表", "交班统计报表", filePath);

                FileDto file = new FileDto("交班统计报表.xls", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                file.FileToken = fileName + ".xls";
                return file;
            }
            catch (Exception ex)
            {
                throw new Exception("导出文件失败");
            }
        }
        #endregion
        #endregion

        #region TbrStatics收费统计报表
        #region 分页查询
        /// <summary>
        /// TbrStatics收费统计报表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrStaticsQuery)]
        public YardPagedResult<TbrStatics> TbrStaticsGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrStaticsInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrStaticsInput>(json);
                YardPagedResult<TbrStatics> pr = _aiYardDbTableIssuedCard.GetTbrStatics(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<TbrStatics>();
            }

        }
        #endregion
        #region 收费统计报表
        /// <summary>
        /// 收费统计报表
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrStaticsExportExcel)]
        public async Task<FileDto> TbrStaticsGetToExcel(string json)
        {
            //try
            //{
            json = json.Replace("undefined", "");
            TbrStaticsInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrStaticsInput>(json);
            List<TbrStatics> pr = _aiYardDbTableIssuedCard.ExportTbrStatics(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByTbrStatics(pr, tc.StaticType);
            //}
            //catch (Exception e)
            //{
            //    return new FileDto();
            //}
        }
        #endregion
        #endregion

        #region TbrStatics收费统计报表2
        #region 分页查询2
        /// <summary>
        /// TbrStatics收费统计报表2
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrStaticsQuery2)]
        public YardPagedResult2<DataTable> TbrStaticsGetPaged2(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrStaticsInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrStaticsInput>(json);
                YardPagedResult2<DataTable> pr = _aiYardDbTableIssuedCard.GetTbrStatics2(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult2<DataTable>();
            }

        }
        #endregion
        #region 收费统计报表2
        /// <summary>
        /// 收费统计报表2
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrStaticsExportExcel2)]
        public async Task<FileDto> TbrStaticsGetToExcel2(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrStaticsInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrStaticsInput>(json);
                DataTable pr = _aiYardDbTableIssuedCard.ExportTbrStatics2(tc, getBAccountQuery());
                if (pr == null || pr.Rows.Count <= 0)
                {
                    throw new Exception("无数据，请先查询再导入");
                }
                string fileName = Guid.NewGuid().ToString("D");
                string webRootPath = _env.WebRootPath;
                var fileDire = webRootPath + string.Format("/Temp/Downloads/", "");
                if (!Directory.Exists(fileDire))
                {
                    Directory.CreateDirectory(fileDire);
                }

                var filePath = fileDire + fileName + ".xls";

                AiYardDbNPOIExcel excel = new AiYardDbNPOIExcel();

                string D = tc.StaticType;

                excel.ToExcel(pr, "收费统计报表按" + D, "收费统计报表按" + D, filePath);

                FileDto file = new FileDto("收费统计报表按" + D + ".xls", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                file.FileToken = fileName + ".xls";
                return file;
            }
            catch (Exception e)
            {
                throw new Exception("导出文件失败");
            }
        }
        #endregion
        #endregion

        #region TbrStatics收费统计报表3
        #region 分页查询3
        /// <summary>
        /// TbrStatics收费统计报表3
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrStaticsQuery3)]
        public YardPagedResult2<DataTable> TbrStaticsGetPaged3(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrStaticsInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrStaticsInput>(json);
                YardPagedResult2<DataTable> pr = _aiYardDbTableIssuedCard.GetTbrStatics3(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult2<DataTable>();
            }

        }
        #endregion
        #region 收费统计报表3
        /// <summary>
        /// 收费统计报表2
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrStaticsExportExcel3)]
        public async Task<FileDto> TbrStaticsGetToExcel3(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrStaticsInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrStaticsInput>(json);
                DataTable pr = _aiYardDbTableIssuedCard.ExportTbrStatics3(tc, getBAccountQuery());
                if (pr == null || pr.Rows.Count <= 0)
                {
                    throw new Exception("无数据，请先查询再导入");
                }
                string fileName = Guid.NewGuid().ToString("D");
                string webRootPath = _env.WebRootPath;
                var fileDire = webRootPath + string.Format("/Temp/Downloads/", "");
                if (!Directory.Exists(fileDire))
                {
                    Directory.CreateDirectory(fileDire);
                }

                var filePath = fileDire + fileName + ".xls";

                AiYardDbNPOIExcel excel = new AiYardDbNPOIExcel();

                string D = tc.StaticType;

                excel.ToExcel(pr, "收费按日班次统计表", "收费按日班次统计表", filePath);

                FileDto file = new FileDto("收费按日班次统计表.xls", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                file.FileToken = fileName + ".xls";
                return file;
            }
            catch (Exception e)
            {
                throw new Exception("导出文件失败");
            }
        }
        #endregion
        #endregion

        #region TbrOnlinePay在线支付查询
        #region 分页查询
        /// <summary>
        /// TbrOnlinePay在线支付查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrOnlinePayQuery)]
        public YardPagedResult<TbrOnlinePay> TbrOnlinePayGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrOnlinePayInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrOnlinePayInput>(json);
                YardPagedResult<TbrOnlinePay> pr = _aiYardDbTableIssuedCard.GetTbrOnlinePay(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<TbrOnlinePay>();
            }

        }
        #endregion
        #region 在线支付查询
        /// <summary>
        /// 在线支付导出
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrOnlinePayExportExcel)]
        public async Task<FileDto> TbrOnlinePayGetToExcel(string json)
        {
            //try
            //{
            json = json.Replace("undefined", "");
            TbrOnlinePayInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrOnlinePayInput>(json);
            List<TbrOnlinePay> pr = _aiYardDbTableIssuedCard.ExportTbrOnlinePay(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByTbrOnlinePay(pr);
            //}
            //catch (Exception e)
            //{
            //    return new FileDto();
            //}
        }
        #endregion
        #endregion

        #region TbrInvoice开票结果查询
        #region 分页查询
        /// <summary>
        /// TbrOnlinePay在线支付查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrInvoiceQuery)]
        public YardPagedResult<TbrInvoice> TbrInvoiceGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrInvoiceInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrInvoiceInput>(json);
                YardPagedResult<TbrInvoice> pr = _aiYardDbTableIssuedCard.GetTbrInvoice(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<TbrInvoice>();
            }

        }
        #endregion
        #region 开票结果导出
        /// <summary>
        /// 开票结果导出
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrInvoiceExportExcel)]
        public async Task<FileDto> TbrInvoiceGetToExcel(string json)
        {
            //try
            //{
            json = json.Replace("undefined", "");
            TbrInvoiceInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrInvoiceInput>(json);
            List<TbrInvoice> pr = _aiYardDbTableIssuedCard.ExportTbrInvoice(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByTbrInvoice(pr);
            //}
            //catch (Exception e)
            //{
            //    return new FileDto();
            //}
        }
        #endregion
        #endregion

        #region TbrInvoice删除开票记录  
        /// <summary>
        /// 删除开票记录
        /// </summary>
        /// <param name="delkeys"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.TbrInvoiceBatchDelete)]
        public bool DeleteInvoice(List<int> delkeys)
        {
            return _aiYardDbTableIssuedCard.DeleteInvoiceRecord(delkeys);
        }
        #endregion

        #region rRoadPayResults路政对账单
        #region 分页查询
        /// <summary>
        /// TbrOnlinePay在线支付查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.rRoadPayResultsQuery)]
        public YardPagedResult<rRoadPayResults> rRoadPayResultsGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                rRoadPayResultsInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<rRoadPayResultsInput>(json);
                YardPagedResult<rRoadPayResults> pr = _aiYardDbTableIssuedCard.GetrRoadPayResults(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<rRoadPayResults>();
            }

        }
        #endregion
        #region 路政对账单查询
        /// <summary>
        /// 在线支付导出
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.rRoadPayResultsExportExcel)]
        public async Task<FileDto> rRoadPayResultsGetToExcel(string json)
        {
             
            json = json.Replace("undefined", "");
            rRoadPayResultsInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<rRoadPayResultsInput>(json);
            List<rRoadPayResults> pr = _aiYardDbTableIssuedCard.ExportrRoadPayResults(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByrRoadPayResults(pr);
            
        }
        #endregion
        #region 下载数据
        [AbpAuthorize(TbrInYardPermissions.rRoadPayResultsDownload)]
        public async Task<string> rRoadPayResultsDownload(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                rRoadPayResultsInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<rRoadPayResultsInput>(json); 
                DateTime dateTime = (DateTime)tc.B;
                while (dateTime <= tc.E)
                {
                    string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
                    host = "localhost"; 
#endif
                    string Url1 = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardRoad/roadpayresults?StationId=" + tc.StationId + "&payDate=" + dateTime.ToString("yyyy-MM-dd"); 
                    string jLQr1 = _httpService.Get(Url1).Trim();   
                    ApiResult jLQr11 = Json.ToObject<ApiResult>(jLQr1);
                    dateTime = dateTime.AddDays(1);
                }
                return "下载完成";
            }
            catch (Exception ex)
            {
                return "下载异常";
            }
        }
        #endregion
        #endregion

        #region rRoadbillInfos路政票证信息
        #region 分页查询
        /// <summary>
        /// TbrOnlinePay在线支付查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.rRoadbillInfosQuery)]
        public YardPagedResult<rRoadbillInfos> rRoadbillInfosGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                rRoadbillInfosInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<rRoadbillInfosInput>(json);
                YardPagedResult<rRoadbillInfos> pr = _aiYardDbTableIssuedCard.GetrRoadbillInfos(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<rRoadbillInfos>();
            }

        }
        #endregion
        #region 路政票证信息
        /// <summary>
        /// 在线支付导出
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.rRoadbillInfosExportExcel)]
        public async Task<FileDto> rRoadbillInfosGetToExcel(string json)
        {

            json = json.Replace("undefined", "");
            rRoadbillInfosInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<rRoadbillInfosInput>(json);
            List<rRoadbillInfos> pr = _aiYardDbTableIssuedCard.ExportrRoadbillInfos(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByrRoadbillInfos(pr);

        }
        #endregion
        #region 下载数据
        [AbpAuthorize(TbrInYardPermissions.rRoadbillInfosDownload)]
        public async Task<string> rRoadbillInfosDownload(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                rRoadbillInfosInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<rRoadbillInfosInput>(json);
                DateTime dateTime = (DateTime)tc.B;
                while (dateTime <= tc.E)
                {
                    string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
                    host = "localhost";
#endif
                    string Url1 = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardRoad/roadbillinfos?StationId=" + tc.StationId + "&billDate=" + dateTime.ToString("yyyy-MM-dd");
                    string jLQr1 = _httpService.Get(Url1).Trim();
                    ApiResult jLQr11 = Json.ToObject<ApiResult>(jLQr1);
                    dateTime = dateTime.AddDays(1);
                }
                return "下载完成";
            }
            catch (Exception ex)
            {
                return "下载异常";
            }
        }
        #endregion
        #endregion

        #region rRoadStagger路政错峰停车签约信息
        #region 分页查询
        /// <summary>
        /// TbrOnlinePay在线支付查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.rRoadStaggerQuery)]
        public YardPagedResult<rRoadStagger> rRoadStaggerGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                rRoadStaggerInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<rRoadStaggerInput>(json);
                YardPagedResult<rRoadStagger> pr = _aiYardDbTableIssuedCard.GetrRoadStagger(tc, getBAccountQuery());

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult<rRoadStagger>();
            }

        }
        #endregion
        #region 路政错峰停车签约信息
        /// <summary>
        /// 在线支付导出
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.rRoadStaggerExportExcel)]
        public async Task<FileDto> rRoadStaggerGetToExcel(string json)
        {

            json = json.Replace("undefined", "");
            rRoadStaggerInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<rRoadStaggerInput>(json);
            List<rRoadStagger> pr = _aiYardDbTableIssuedCard.ExportrRoadStagger(tc, getBAccountQuery());
            if (pr == null || pr.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            return _listExcelExporter.ExportToExcelByrRoadStagger(pr);

        }
        #endregion
        #region 下载数据
        [AbpAuthorize(TbrInYardPermissions.rRoadStaggerDownload)]
        public async Task<string> rRoadStaggerDownload(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                rRoadStaggerInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<rRoadStaggerInput>(json);
                DateTime dateTime = (DateTime)tc.B;
                while (dateTime <= tc.E)
                {
                    string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
                    host = "localhost"; 
#endif
                    string Url1 = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardRoad/roadstagger?StationId=" + tc.StationId + "&queryDate=" + dateTime.ToString("yyyy-MM-dd");
                    string jLQr1 = _httpService.Get(Url1).Trim();
                    ApiResult jLQr11 = Json.ToObject<ApiResult>(jLQr1);
                    dateTime = dateTime.AddDays(1);
                }
                return "下载完成";
            }
            catch (Exception ex)
            {
                return "下载异常";
            }
        }
        #endregion
        #endregion

        #region rStatisticsCL车流统计查询
        #region 分页查询
        /// <summary>
        /// rStatisticsCL车流统计查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.rStatisticsCLQuery)]
        public YardPagedResult2<DataTable> rStatisticsCLGetPaged(string json)
        {
            try
            {
                json = json.Replace("undefined", "");
                TbrStaticsCLInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrStaticsCLInput>(json);
                YardPagedResult2<DataTable> pr = _aiYardDbTableIssuedCard.GetTbrStatisticsCL(tc);

                return pr;
            }
            catch (Exception e)
            {
                return new YardPagedResult2<DataTable>();
            }

        }
        #endregion
        #region 车流统计查询导出
        /// <summary>
        /// 车流统计查询导出
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbrInYardPermissions.rStatisticsCLExportExcel)]
        public async Task<FileDto> rStatisticsCLGetToExcel(string json)
        {

            json = json.Replace("undefined", "");
            TbrStaticsCLInput tc = JYJ.AiYard.StationManagement.YardCommonHald.Json.ToObject<TbrStaticsCLInput>(json);
            DataTable pr = _aiYardDbTableIssuedCard.ExportTbrStatisticsCL(tc);
            if (pr == null || pr.Rows.Count <= 0)
            {
                throw new Exception("无数据，请先查询再导入");
            }
            string fileName = Guid.NewGuid().ToString("D");
            string webRootPath = _env.WebRootPath;
            var fileDire = webRootPath + string.Format("/Temp/Downloads/", "");
            if (!Directory.Exists(fileDire))
            {
                Directory.CreateDirectory(fileDire);
            }

            var filePath = fileDire + fileName + ".xls";

            AiYardDbNPOIExcel excel = new AiYardDbNPOIExcel();
            if (tc.RType == 1)
            {
                excel.ToExcel(pr, "车流量统计表", "车流量统计表", filePath,false);
                FileDto file = new FileDto("车流量统计表.xls", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                file.FileToken = fileName + ".xls";
                return file;
            }
            else if (tc.RType == 2)
            {
                excel.ToExcel(pr, "停放时间统计表", "停放时间统计表", filePath, false);
                FileDto file = new FileDto("停放时间统计表.xls", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                file.FileToken = fileName + ".xls";
                return file;
            }
            else
            {
                excel.ToExcel(pr, "按周车流统计表", "按周车流统计表", filePath, false);
                FileDto file = new FileDto("按周车流统计表.xls", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                file.FileToken = fileName + ".xls";
                return file;
            }
            

        }
        #endregion
         
        #endregion


        #region 获取当前租户下面的所有场所
        /// <summary>
        /// 获取当前租户下面的所有场所
        /// </summary>
        /// <returns></returns>
        public async Task<List<TbStationSelectDto>> GetAllStationByTenantID()
        {
            int TenantID = 0;
            if (!Convert.IsDBNull(AbpSession.TenantId))
                TenantID = Convert.ToInt32(AbpSession.TenantId);

            List<TbStation> tbStations = new List<TbStation>();
            var allOrganizationUnits = await _userApp.GetAllOrganizationUnitList();
            var Org = allOrganizationUnits.MapTo<ListResultDto<OrganizationUnitListDto>>();
            foreach (var orgzation in Org.Items)
            {
                var station = _aiYardDbTableIssuedCard.GetTbStations(orgzation.Id);
                if (station != null && station.Count > 0)
                { tbStations.Add(station[0]); }
            }

            var entityListDto = tbStations.OrderBy(o => o.Station_Name).MapTo<List<TbStationSelectDto>>();
            return entityListDto;
        }
        #endregion

        #region 获取当前场所下的所有商户
        /// <summary>
        /// 获取当前场所下的所有商户
        /// </summary>
        /// <returns></returns>
        public List<TbSaleSelectDto> GetAllSalesByStationID(long StationId)
        {
            long SaleID = _aiYardDbTableIssuedCard.IsUserOrganizationUnit(Convert.ToInt64(AbpSession.UserId));
            if (SaleID > 0)
            {
                var entity = _aiYardDbTableIssuedCard.GetAllSalesByStationID(StationId).Where(o => o.Id == SaleID);

                var entityListDto = entity.MapTo<List<TbSaleSelectDto>>();
                return entityListDto;
            }
            else
            {
                var entity = _aiYardDbTableIssuedCard.GetAllSalesByStationID(StationId);

                var entityListDto = entity.MapTo<List<TbSaleSelectDto>>();
                return entityListDto;
            }
        }
        #endregion

        #region 获取当前场所下所有免单券类型
        public List<string> GetAllBillNameByStationID(long StationId)
        {
            var entity = _aiYardDbTableIssuedCard.GetAllBillNameByStationID(StationId);
            var entityListDto = entity.MapTo<List<string>>();
            return entityListDto;
        }
        #endregion

        #region 获取当前场所所有注册客户端
        public List<TbClientRegisterSelectDto> GetAllClientByStationID(long StationId)
        {

            List<TbClientRegister> clients = new List<TbClientRegister>();
            if (StationId != 0)
            {
                List<long> Station_Id = new List<long>();
                Station_Id.Add(StationId);
                clients = _aiYardDbTableIssuedCard.GetTbClientRegister(Station_Id, "");
            }
            else
            {
                clients = _aiYardDbTableIssuedCard.GetTbClientRegister(null, "");
            }
            List<TbClientRegisterSelectDto> allclients = new List<TbClientRegisterSelectDto>();
            foreach (TbClientRegister register in clients)
            {
                TbClientRegisterSelectDto selectDto = new TbClientRegisterSelectDto();
                selectDto.Client_ID = register.Client_ID;
                selectDto.Client_Name = register.Client_Name;
                selectDto.Client_Type = register.Client_Type;
                selectDto.Id = register.Id;
                allclients.Add(selectDto);
            }
            return allclients;
        }
        #endregion

        #region 获取当前场所所有岗亭操作用户
        public List<TbrGTOpUser> GetAllOpUser(long StationId)
        {
            List<long> Station_Id = new List<long>();
            Station_Id.Add(StationId);
            return _aiYardDbTableIssuedCard.GetTbGTUser(Station_Id);
        }
        #endregion

        #region 获取当前场所所有收费类型
        public List<string> GetAllCardType(long StationId)
        {
            List<long> Station_Id = new List<long>();
            Station_Id.Add(StationId);
            return _aiYardDbTableIssuedCard.GetTbCardType(Station_Id);
        }
        #endregion

        #region 获取当前场所所有出场通道
        public List<TbrOutMach> GetAllOutMach(long StationId)
        {
            List<long> Station_Id = new List<long>();
            Station_Id.Add(StationId);
            return _aiYardDbTableIssuedCard.GetOutMach(Station_Id);
        }
        #endregion

        #region 获取当前场所下所有部门
        public async Task<List<TbrYardDepart>> GetAllDepartByTenantID()
        {
            return _aiYardDbTableIssuedCard.GetDepartList(GetCurrenUserOrganizationAndChildrenUnit());
        }
        #endregion

        #region 获取是否有B账查看权限
        public bool getBAccountQuery()
        {
            try
            {
                return _aiYardDbTableIssuedCard.isBAccountQuery((long)AbpSession.UserId);
            }
            catch
            {
                return false;
            }
        }
        #endregion
    }
}
